package org.sample.springbootredis.config;

import org.sample.springbootcommon.utils.EncodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCachePrefix;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class CachingConfigurer extends CachingConfigurerSupport {

	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;

	@Bean
	@Override
	public CacheManager cacheManager() {
		RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
		redisCacheManager.afterPropertiesSet();
		// redisCacheManager.setExpires(cacheTimeoutExpiresMap);
		redisCacheManager.setDefaultExpiration(10000);
		redisCacheManager.setUsePrefix(true);
		redisCacheManager.setCachePrefix(new RedisCachePrefix() {
			private static final String DELIMITER = ":";
			private final RedisSerializer<String> serializer = new StringRedisSerializer();

			@Override
			public byte[] prefix(String cacheName) {
				return serializer.serialize("SAMPLE_CACHE".concat(DELIMITER).concat(cacheName).concat(DELIMITER));
			}
		});
		return redisCacheManager;
	}

	@Bean
	@Override
	public KeyGenerator keyGenerator() {
		return (target, method, params) -> {
			StringBuilder sb = new StringBuilder();
			sb.append(target.getClass().getSimpleName());
			sb.append(".");
			sb.append(method.getName());
			for (Object param : params) {
				sb.append("-");
				sb.append(EncodeUtils.toJsonDigestBase64(param));
			}
			return EncodeUtils.toDigestBase64(sb.toString());
		};
	}

}
